<template>
  <section>
    <el-table
      style="width: 100%"
      border
      id="iTable"
      v-loading.iTable="options.loading"
      :data="list"
      :stripe="options.stripe"
      row-key="$index"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      ref="mutipleTable"
      @selection-change="handleSelectionChange"
      empty-text=" "
      :header-cell-style="{ background: '#F6F8FB' }"
      :max-height="maxHeight"
      v-scrollbar="'.el-table__body-wrapper'"
      :show-summary="options.showSummary"
      :summary-method="getSummaries"
    >
      <!--选择框-->
      <el-table-column
        v-if="options.mutiSelect"
        type="selection"
        width="60"
        align="center"
        :selectable="checkboxInit"
      >
      </el-table-column>
      <!--end-->
      <!--数据列-->
      <template v-for="(column, index) in columns">
        <template v-if="column.prop.indexOf('{') > -1">
          <template v-for="n in 10">
            <el-table-column
              :show-overflow-tooltip="column.showOverflow"
              :prop="column.prop.replace(/{id}/g, String(n))"
              :key="column.prop.replace(/{id}/g, String(n))"
              :label="column.name + String(n)"
              :align="column.align"
              :width="hasResize ? column.showWidth : column.width"
              :sortable="column.sortable"
              v-if="
                list[0][column.prop.replace(/{id}/g, String(n))] && column.show
              "
            >
              <template slot-scope="scope">
                <template v-if="column.fullEdit && editall">
                  <template v-if="addFormData[column.prop] != undefined">
                    <dynamic-form-item
                      :addform="[addFormData[column.prop]]"
                      :form="scope.row"
                    >
                    </dynamic-form-item>
                  </template>
                  <template v-else>
                    <el-input v-model="scope.row[column.prop]"></el-input>
                  </template>
                </template>
                <template v-else>
                  <template v-if="!column.render">
                    <template v-if="column.propType === 'list'">
                      <template
                        v-if="
                          scope.row[column.prop] &&
                            scope.row[column.prop].length >= 1
                        "
                      >
                        <el-dropdown placement="bottom">
                          <span class="el-dropdown-link">
                            {{ scope.row[column.prop].length }}
                            <i class="el-icon-arrow-down el-icon--right"></i>
                          </span>
                          <el-dropdown-menu
                            slot="dropdown"
                            v-scrollbar
                            style="
                            max-height: 300px;
                            overflow: hidden;
                            z-index: 1000;
                          "
                          >
                            <template v-for="file in scope.row[column.prop]">
                              <el-dropdown-item
                                class="item"
                                :key="file.id"
                                :command="file"
                              >
                                <a
                                  style="text-decoration: underline; color: #409eff"
                                  @click="
                                    preview(
                                      file.path,
                                      scope.row['stateid'],
                                      scope.row['id'],
                                      file.id
                                    )
                                  "
                                >
                                  {{ file.name }}
                                </a>
                              </el-dropdown-item>
                            </template>
                          </el-dropdown-menu>
                        </el-dropdown>
                      </template>
                      <template v-else>
                        0
                      </template>
                      <!-- <div
                      v-for="(item, index) in scope.row[column.prop]"
                      :key="index"
                    >
                      <a
                        style="text-decoration: underline; color: #409eff"
                        @click="
                          preview(
                            item.path,
                            scope.row['stateid'],
                            scope.row['docId']
                          )
                        "
                      >
                        {{ item.fileName }}
                      </a>
                    </div> -->
                    </template>
                    <template v-else-if="column.propType === 'preview'">
                      <a
                        style="text-decoration: underline; color: #409eff"
                        @click="
                          preview(
                            scope.row.path,
                            scope.row.stateid,
                            scope.row.docId,
                            scope.row.id
                          )
                        "
                      >
                        {{ scope.row[column.prop] }}
                      </a>
                    </template>
                    <template v-else-if="column.propType === 'date'">
                      {{
                        scope.row[column.prop]
                          ? scope.row[column.prop].split(' ')[0]
                          : ' '
                      }}
                    </template>
                    <template v-else-if="column.propType === 'link'">
                      <span
                        class="link-type"
                        @click="jumpTo(scope.row, column)"
                        >{{ scope.row[column.prop] }}</span
                      >
                    </template>
                    <template v-else-if="column.propType === 'file'">
                      <a
                        style="text-decoration: underline; color: #409eff"
                        @click="
                          preview(
                            scope.row[column.prop].path,
                            scope.row.stateid,
                            scope.row.docId,
                            scope.row.id
                          )
                        "
                      >
                        {{ scope.row[column.prop].fileName }}
                      </a>
                    </template>
                    <template v-else-if="column.propType === 'button'">
                      <span
                        v-if="column.url"
                        @click="
                          clickEvent(
                            {
                              url: column.url,
                              pageParams: column.pageParams,
                              type: 1,
                              name: column.name
                            },
                            scope.row
                          )
                        "
                      >
                        {{ scope.row[column.prop] }}
                        <i class="el-icon-plus"></i>
                      </span>
                      <span
                        class="link-type"
                        v-else
                        @click="
                          clickEvent(
                            {
                              pageParams: column.pageParams,
                              type: 1,
                              name: column.name
                            },
                            scope.row
                          )
                        "
                      >
                        {{ scope.row[column.prop] }}
                      </span>
                    </template>
                    <template v-else-if="column.propType === 'progress'">
                      <el-progress
                        :text-inside="true"
                        :stroke-width="26"
                        :percentage="scope.row[column.prop]"
                      >
                      </el-progress>
                    </template>
                    <template v-else-if="column.propType === 'rate'">
                      <el-rate
                        disabled
                        text-color="#ff9900"
                        :value="
                          scope.row[column.prop] ? scope.row[column.prop] : 0
                        "
                        show-score
                      >
                      </el-rate>
                    </template>
                    <template v-else-if="column.propType === 'image'">
                      <img
                        v-if="scope.row[column.prop]"
                        :src="JSON.parse(scope.row[column.prop])[0].path"
                        alt="图片"
                        style="width: 20px; height: 20px"
                        @click="
                          imgPreview(
                            JSON.parse(scope.row[column.prop]).map(
                              item => item.path
                            )
                          )
                        "
                      />
                    </template>
                    <template v-else-if="column.propType === 'icon'">
                      <img
                        :src="dynamicEval(scope.row, column.pageParams)"
                        alt="图标"
                      />
                    </template>
                    <template v-else-if="column.propType === 'user'">
                      {{
                        scope.row[column.prop]
                          ? $store.state.optionInfo.Users.filter(
                              item => item.userId == scope.row[column.prop]
                            )[0].userName
                          : ''
                      }}
                    </template>
                    <template v-else-if="column.propType === 'role'">
                      {{
                        scope.row[column.prop]
                          ? $store.state.optionInfo.Roles.filter(
                              item => item.roleId == scope.row[column.prop]
                            ).length == 1
                            ? $store.state.optionInfo.Roles.filter(
                                item => item.roleId == scope.row[column.prop]
                              )[0].roleName
                            : ''
                          : ''
                      }}
                      <!-- {{scope.row[column.prop]}} -->
                    </template>
                    <template v-else-if="column.propType === 'select'">
                      <template v-if="!scope.row['roleId']">
                        {{ dataFormat('ownerid', scope.row[column.prop]) }}
                      </template>
                      <template v-else>
                        <template
                          v-if="
                            $store.state.optionInfo.Users.filter(
                              item =>
                                (item.roleIds &&
                                  item.roleIds.includes(scope.row['roleId'])) ||
                                (scope.row[column.prop] &&
                                  item.userId === scope.row[column.prop])
                            ).length > 0
                          "
                        >
                          <el-select
                            v-model="scope.row[column.prop]"
                            filterable
                            @change="handleChange(scope.row)"
                          >
                            <el-option
                              v-for="item in $store.state.optionInfo.Users.filter(
                                item =>
                                  item.roleIds.includes(scope.row['roleId'])
                              )"
                              :key="item.userId"
                              :label="item.userName"
                              :value="item.userId"
                            >
                            </el-option>
                          </el-select>
                        </template>
                      </template>
                    </template>
                    <template v-else-if="column.propType === 'switch'">
                      <el-switch
                        v-model="scope.row[column.prop]"
                        active-value="0"
                        inactive-value="1"
                        @change="handleStatusChange(scope.row, column)"
                      ></el-switch>
                    </template>
                    <template v-else-if="column.propType === 'tag'">
                      <el-tag>{{
                        dataFormat(column.prop, scope.row[column.prop])
                      }}</el-tag>
                    </template>
                    <template v-else>
                      <span v-if="!Array.isArray(scope.row[column.prop])">
                        {{ dataFormat(column.prop, scope.row[column.prop]) }}
                      </span>
                    </template>
                  </template>
                  <template v-else>
                    <expand-dom
                      :column="column"
                      :row="scope.row"
                      :render="column.render"
                      :index="index"
                    >
                    </expand-dom>
                  </template>
                </template>
              </template>
            </el-table-column>
          </template>
        </template>
        <template v-else>
          <el-table-column
            :show-overflow-tooltip="column.showOverflow"
            :prop="column.prop"
            :key="column.prop"
            :label="column.name"
            :align="column.align"
            :width="hasResize ? column.showWidth : column.width"
            :sortable="column.sortable"
            v-if="column.show"
          >
            <template slot-scope="scope">
              <template v-if="column.fullEdit && editall">
                <template v-if="addFormData[column.prop] != undefined">
                  <dynamic-form-item
                    :addform="[addFormData[column.prop]]"
                    :form="scope.row"
                  >
                  </dynamic-form-item>
                </template>
                <template v-else>
                  <el-input v-model.number="scope.row[column.prop]"></el-input>
                </template>
              </template>
              <template v-else>
                <template v-if="!column.render">
                  <template v-if="column.propType === 'list'">
                    <template
                      v-if="
                        scope.row[column.prop] &&
                          scope.row[column.prop].length >= 1
                      "
                    >
                      <el-dropdown placement="bottom">
                        <span class="el-dropdown-link">
                          {{ scope.row[column.prop].length }}
                          <i class="el-icon-arrow-down el-icon--right"></i>
                        </span>
                        <el-dropdown-menu
                          slot="dropdown"
                          v-scrollbar
                          style="
                            max-height: 300px;
                            overflow: hidden;
                            z-index: 1000;
                          "
                        >
                          <template v-for="file in scope.row[column.prop]">
                            <el-dropdown-item
                              class="item"
                              :key="file.id"
                              :command="file"
                            >
                              <a
                                style="text-decoration: underline; color: #409eff"
                                @click="
                                  preview(
                                    file.path,
                                    scope.row['stateid'],
                                    scope.row['id'],
                                    file.id
                                  )
                                "
                              >
                                {{ file.name }}
                              </a>
                            </el-dropdown-item>
                          </template>
                        </el-dropdown-menu>
                      </el-dropdown>
                    </template>
                    <template v-else>
                      0
                    </template>
                    <!-- <div
                      v-for="(item, index) in scope.row[column.prop]"
                      :key="index"
                    >
                      <a
                        style="text-decoration: underline; color: #409eff"
                        @click="
                          preview(
                            item.path,
                            scope.row['stateid'],
                            scope.row['docId']
                          )
                        "
                      >
                        {{ item.fileName }}
                      </a>
                    </div> -->
                  </template>
                  <template v-else-if="column.propType === 'preview'">
                    <a
                      style="text-decoration: underline; color: #409eff"
                      @click="
                        preview(
                          scope.row.path,
                          scope.row.stateid,
                          scope.row.docId,
                          scope.row.id
                        )
                      "
                    >
                      {{ scope.row[column.prop] }}
                    </a>
                  </template>
                  <template v-else-if="column.propType === 'file'">
                    <template
                      v-if="
                        scope.row[column.prop] != null &&
                          scope.row[column.prop] != {}
                      "
                    >
                      <a
                        style="text-decoration: underline; color: #409eff"
                        @click="
                          preview(
                            scope.row[column.prop].path,
                            scope.row.stateid,
                            scope.row.docId,
                            scope.row.id
                          )
                        "
                      >
                        {{ scope.row[column.prop].fileName }}
                      </a>
                    </template>
                  </template>
                  <template v-else-if="column.propType === 'date'">
                    {{
                      scope.row[column.prop]
                        ? scope.row[column.prop].split(' ')[0]
                        : ' '
                    }}
                  </template>
                  <template v-else-if="column.propType === 'link'">
                    <span
                      class="link-type"
                      @click="jumpTo(scope.row, column)"
                      >{{ scope.row[column.prop] }}</span
                    >
                  </template>
                  <template v-else-if="column.propType === 'button'">
                    <span
                      v-if="column.url"
                      @click="
                        clickEvent(
                          {
                            url: column.url,
                            pageParams: column.pageParams,
                            type: 1,
                            name: column.name
                          },
                          scope.row
                        )
                      "
                    >
                      {{ scope.row[column.prop] }}
                      <i class="el-icon-plus"></i>
                    </span>
                    <span
                      class="link-type"
                      v-else
                      @click="
                        clickEvent(
                          {
                            pageParams: column.pageParams,
                            type: 1,
                            name: column.name
                          },
                          scope.row
                        )
                      "
                    >
                      {{ scope.row[column.prop] }}
                    </span>
                  </template>
                  <template v-else-if="column.propType === 'progress'">
                    <el-progress
                      :text-inside="true"
                      :stroke-width="26"
                      :percentage="scope.row[column.prop]"
                    >
                    </el-progress>
                  </template>
                  <template v-else-if="column.propType === 'rate'">
                    <el-rate
                      disabled
                      text-color="#ff9900"
                      :value="
                        scope.row[column.prop] ? scope.row[column.prop] : 0
                      "
                      show-score
                    >
                    </el-rate>
                  </template>
                  <template v-else-if="column.propType === 'image'">
                    <img
                      v-if="scope.row[column.prop]"
                      :src="JSON.parse(scope.row[column.prop])[0].path"
                      alt="图片"
                      style="width: 20px; height: 20px"
                      @click="
                        imgPreview(
                          JSON.parse(scope.row[column.prop]).map(
                            item => item.path
                          )
                        )
                      "
                    />
                  </template>
                  <template v-else-if="column.propType === 'icon'">
                    <img
                      v-if="dynamicEval(scope.row, column.pageParams)"
                      :src="dynamicEval(scope.row, column.pageParams)"
                      alt="图标"
                    />
                  </template>
                  <template v-else-if="column.propType === 'user'">
                    {{
                      scope.row[column.prop]
                        ? $store.state.optionInfo.Users.filter(
                            item => item.userId == scope.row[column.prop]
                          )[0].userName
                        : ''
                    }}
                  </template>
                  <template v-else-if="column.propType === 'role'">
                    {{
                      scope.row[column.prop]
                        ? $store.state.optionInfo.Roles.filter(
                            item => item.roleId == scope.row[column.prop]
                          ).length == 1
                          ? $store.state.optionInfo.Roles.filter(
                              item => item.roleId == scope.row[column.prop]
                            )[0].roleName
                          : ''
                        : ''
                    }}
                    <!-- {{scope.row[column.prop]}} -->
                  </template>
                  <template v-else-if="column.propType === 'select'">
                    <template v-if="!scope.row['roleId']">
                      {{ dataFormat('ownerid', scope.row[column.prop]) }}
                    </template>
                    <template v-else>
                      <template
                        v-if="
                          $store.state.optionInfo.Users.filter(
                            item =>
                              (item.roleIds &&
                                item.roleIds.includes(scope.row['roleId'])) ||
                              (scope.row[column.prop] &&
                                item.userId === scope.row[column.prop])
                          ).length > 0
                        "
                      >
                        <el-select
                          v-model="scope.row[column.prop]"
                          filterable
                          @change="handleChange(scope.row)"
                        >
                          <el-option
                            v-for="item in $store.state.optionInfo.Users.filter(
                              item => item.roleIds.includes(scope.row['roleId'])
                            )"
                            :key="item.userId"
                            :label="item.userName"
                            :value="item.userId"
                          >
                          </el-option>
                        </el-select>
                      </template>
                    </template>
                  </template>
                  <template v-else-if="column.propType === 'switch'">
                    <el-switch
                      v-model="scope.row[column.prop]"
                      active-value="0"
                      inactive-value="1"
                      @change="handleStatusChange(scope.row, column)"
                    ></el-switch>
                  </template>
                  <template v-else-if="column.propType === 'tag'">
                    <el-tag>{{
                      dataFormat(column.prop, scope.row[column.prop])
                    }}</el-tag>
                  </template>
                  <template v-else>
                    <span v-if="!Array.isArray(scope.row[column.prop])">
                      {{ dataFormat(column.prop, scope.row[column.prop]) }}
                    </span>
                  </template>
                </template>
                <template v-else>
                  <expand-dom
                    :column="column"
                    :row="scope.row"
                    :render="column.render"
                    :index="index"
                  >
                  </expand-dom>
                </template>
              </template>
            </template>
          </el-table-column>
        </template>
      </template>
      <!--end-->
      <!--按钮操作组-->
      <el-table-column
        ref="fixedColumn"
        fixed="right"
        label="操作"
        align="center"
        :width="
          operates.list.filter(_x => _x.status === '1' && _x.location === '1')
            .length <= 3
            ? operates.list.filter(
                _x => _x.status === '1' && _x.location === '1'
              ).length *
                40 +
              60
            : 100
        "
        v-if="
          operates.list.filter(_x => _x.status === '1' && _x.location === '1')
            .length > 0
        "
      >
        <template slot="header" slot-scope="scope">
          操作
          <el-button
            v-if="editall && showAdd"
            @click="handleAddLine"
            size="mini"
            type="primary"
            round
            style="right:5%"
            >新增行</el-button
          >
        </template>
        <template slot-scope="scope" v-if="!editall">
          <el-dropdown
            v-if="
              operates.list.filter(
                _x => _x.status === '1' && _x.location === '1'
              ).length > 3
            "
            @command="handleCommand"
          >
            <span class="el-dropdown-link">
              操作选择
              <i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <template v-for="btn in operates.list">
                <el-dropdown-item
                  class="item"
                  v-if="btn.status === '1' && btn.location === '1'"
                  v-show="
                    btn.show != null && btn.show != undefined && btn.show != ''
                      ? dynamicEval(scope.row, btn.show)
                      : true
                  "
                  :key="btn.id"
                  :command="{ btn, row: scope.row }"
                >
                  <el-upload
                    class="upload-demo"
                    :action="upload.url"
                    :file-list="[]"
                    :on-success="
                      (response, file, fileList) => {
                        return handleFileSuccess(
                          response,
                          file,
                          fileList,
                          scope.row,
                          btn
                        )
                      }
                    "
                    :on-error="handleFileError"
                    :headers="upload.headers"
                    :show-file-list="false"
                    :multiple="btn.operateType.indexOf('multi') > -1"
                    v-if="btn.type == '4'"
                  >
                    <el-button
                      size="mini"
                      type="text"
                      :icon="btn.icon"
                      :plain="false"
                      v-if="
                        !(
                          $route.path.indexOf('/outer') > -1 &&
                          btn.name == '删除'
                        )
                      "
                      >{{ btn.name }}
                    </el-button>
                  </el-upload>
                  <template v-else>
                    <el-button
                      size="mini"
                      type="text"
                      :icon="btn.icon"
                      :plain="false"
                      v-if="
                        !(
                          $route.path.indexOf('/outer') > -1 &&
                          btn.name == '删除'
                        )
                      "
                      >{{ btn.name }}
                    </el-button>
                  </template>
                </el-dropdown-item>
              </template>
            </el-dropdown-menu>
          </el-dropdown>
          <div class="operate-group" v-else>
            <div v-for="(btn, index) in operates.list" :key="index">
              <div
                class="item"
                v-if="btn.status === '1' && btn.location === '1'"
                v-show="
                  btn.show != null && btn.show != undefined && btn.show != ''
                    ? dynamicEval(scope.row, btn.show)
                    : true
                "
              >
                <el-upload
                  class="upload-demo"
                  :action="upload.url"
                  :file-list="[]"
                  :on-success="
                    (response, file, fileList) => {
                      return handleFileSuccess(
                        response,
                        file,
                        fileList,
                        scope.row,
                        btn
                      )
                    }
                  "
                  :on-error="handleFileError"
                  :headers="upload.headers"
                  :show-file-list="false"
                  :multiple="btn.operateType.indexOf('multi') > -1"
                  v-if="btn.type == '4'"
                >
                  <span
                    style="cursor: pointer; color: #409eff"
                    size="mini"
                    :class="btn.icon"
                    :plain="false"
                    v-if="
                      !(
                        $route.path.indexOf('/outer') > -1 && btn.name == '删除'
                      )
                    "
                    >{{ btn.name }}
                  </span>
                </el-upload>
                <template v-else>
                  <span
                    style="cursor: pointer; color: #409eff"
                    size="mini"
                    :class="btn.icon"
                    :plain="false"
                    @click="clickEvent(btn, scope.row)"
                    v-if="
                      !(
                        $route.path.indexOf('/outer') > -1 && btn.name == '删除'
                      )
                    "
                    >{{ btn.name }}
                  </span>
                </template>
              </div>
            </div>
          </div>
        </template>
      </el-table-column>
      <!--end-->
    </el-table>
    <el-dialog
      :visible.sync="progress.open"
      v-if="progress.open"
      :before-close="
        () => {
          return false
        }
      "
      title="下载进度"
      width="30%"
    >
      <el-progress
        type="circle"
        :percentage="progress.percent"
        style="margin: 0 10vw"
      ></el-progress>
    </el-dialog>
  </section>
</template>
<!--end-->

<script>
import { getToken } from '@/utils/auth'
import { handleBatchDownload } from '@/utils/zipdownload'
import {
  delData,
  updateData,
  baseRequest,
  permissions,
  permissionsNoState,
  changeStatus
} from '@/api/dynamic/dynamic'
import { addDownload, getDownloadUrl } from '@/api/pms/download'
import dynamicFormItem from '@/views/components/dynamicFormItem'
import Base64 from '@/api/base64'
import resize from '@/views/dashboard/mixins/resize'
import { createUniqueString } from '@/utils'
// import commonFun from "@/views/mixins/commonFun";
export default {
  inject: ['app'],
  name: 'dynamicTable',
  mixins: [resize],
  props: {
    // 数据列表
    list: {
      type: Array,
      default: () => []
    },
    /* 需要展示的列 ===
        prop：列数据对应的属性，
        label：列名，
        align：对齐方式，
        width：列宽
      */
    columns: {
      type: Array,
      default: []
    },
    /* 操作按钮组 ===
        label: 文本，
        type :类型（primary / success / warning / danger / info / text），
        show：是否显示，
        icon：按钮图标，
        plain：是否朴素按钮，
        disabled：是否禁用，
        method：回调方法
      */
    operates: {},
    // table 表格的控制参数
    options: {
      type: Object,
      default: {
        stripe: false, // 是否为斑马纹 table
        highlightCurrentRow: false // 是否要高亮当前行
      }
    },
    diff: 0,
    scroll: {
      type: String,
      default: 'true'
    },
    parent: null,
    uncheck: {
      type: Array,
      default: () => []
    },
    defaultSelect: Object
  },
  //组件
  components: {
    expandDom: {
      functional: true,
      props: {
        row: Object,
        render: Function,
        index: Number,
        column: {
          type: Object,
          default: null
        }
      },
      render: (h, ctx) => {
        const params = {
          row: ctx.props.row,
          index: ctx.props.index
        }
        if (ctx.props.column) params.column = ctx.props.column
        return ctx.props.render(h, params)
      }
    },
    dynamicFormItem
  },
  // 数据
  data() {
    return {
      pageIndex: 1,
      // 多行选中
      multipleSelection: [],
      addFormData: {},
      rend: false,
      progress: {
        open: false,
        percent: 0
      },
      maxHeight: 200,
      hasResize: false,
      // 全编辑控制
      editall: false,
      showAdd: false,
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/common/upload',
        // url: process.env.VUE_APP_BASE_API + "/common/S3upload",
        // 上传的文件列表
        showFileList: [],
        // 大小限制(MB)
        fileSize: 500
      }
    }
  },
  // created() {
  //   if (this.$parent.$el) {
  //     // this.rend = true
  //     this.tableresize();
  //   }
  // },
  mounted() {
    setTimeout(() => {
      if (this.defaultSelect && this.list) {
        for (let item in this.defaultSelect) {
          // this.handleSelectionChange(this.list.filter(i=>this.defaultSelect[item].includes(i[item])))
          // console.log(this.defaultSelect[item])
          for (let row of this.defaultSelect[item]) {
            if (row) {
              if (typeof row == 'string') {
                row = row.trim()
              }
              this.$refs.mutipleTable.toggleRowSelection(
                this.list.filter(i => i[item] == row)[0],
                true
              )
            }
          }
        }
      }
    }, 1000)
  },
  watch: {
    columns: {
      deep: true,
      handler: function(val) {
        this.widthUpdate(val)
      }
    }
  },
  methods: {
    //行点击事件
    jumpTo(row, column) {
      console.log(row, 'row')
      let tempParams = row.pageParams || column.pageParams
      let tempUrl = row.url || column.url
      if (column.url.indexOf('http') > -1) {
        window.open(this.getUrl(column.url, row), '_blank')
        return false
      }
      let params = {}
      let pageParams = JSON.parse(tempParams.replace(/'/g, '"'))
      let item = null
      if (row.previousLevel) {
        let str = 'index_child' + row.projectid
        item = JSON.parse(sessionStorage.getItem(str))
        console.log(item, 'item')
        pageParams = item.pageParams

        // return this.$router.go(-1)
      }
      if (item) {
        params.rowParams =
          pageParams.route.indexOf('projectid') > -1
            ? { name: row.projectName }
            : item.rowParams
      } else {
        params.rowParams =
          pageParams.route.indexOf('projectid') > -1
            ? { name: row.projectName }
            : row
      }

      // params.rowParams = row;
      // params.type = column.url.replace(/\/{id}|\/{projectid}/g, "");
      if (
        this.$route.query.type &&
        this.$route.query.type.indexOf('template') > -1 &&
        params.type == '/pmswbs'
      ) {
        params.edit = 'pmswbs/editTemplateWbs'
      }
      // if(pageParams.route.indexOf('{')>-1){
      //   pageParams.route = this.getUrl(pageParams.route,row);
      //   // console.log(pageParams.route)
      // }else{
      //   pageParams.route = pageParams.route + "/" + row.id
      // }
      // params.rowParams = row;
      if (item) {
        pageParams.url = item.pageParams.url
      } else {
        pageParams.url = tempUrl
      }
      params.pageParams = pageParams
      params.type = pageParams.url.replace(
        /\/[{]([a-zA-Z][a-zA-Z0-9]*)[}]|\/\d+/,
        ''
      )
      console.log(params, ' pageParams.type')
      console.log(pageParams.url, ' pageParams.url')
      if (pageParams.outer) {
        if (pageParams.route.indexOf('{') > -1) {
          var routeData = this.$router.resolve({
            path: '/outer/dynamic/' + this.getUrl(pageParams.route, row),
            query: params
          })
        } else {
          var routeData = this.$router.resolve({
            path: '/outer/dynamic/' + pageParams.route + '/' + row.id,
            query: params
          })
        }
        const newwin = window.open(
          routeData.href,
          createUniqueString(),
          `height=${
            0.5 * this.app.screenHeight > 600
              ? 0.5 * this.app.screenHeight
              : 600
          },width=${
            0.5 * this.app.screenWidth > 960 ? 0.5 * this.app.screenWidth : 960
          },
                    top=${0.2 * this.app.screenHeight},
                     left=${0.2 * this.app.screenWidth}`
        )
        newwin.route = routeData.route
      } else {
        if (pageParams.route.indexOf('{') > -1) {
          this.$router.push({
            path:
              (this.$route.path.indexOf('/outer') > -1 ? '/outer' : '') +
              '/dynamic/' +
              this.getUrl(pageParams.route, row),
            query: params
          })
        } else {
          // console.log(
          //   (this.$route.path.indexOf("/outer") > -1 ? "/outer" : "") +
          //   "/dynamic/" +
          //   pageParams.route +(pageParams.url.match(/\/\d+/).index>-1?pageParams.url.match(/\/\d+/)[0]:
          //     "/" +
          //     row.id))
          // return

          // item.rowParams.id
          let concatStr = ''
          if (pageParams.url.match(/\/\d+/)) {
            params.rowParams = { name: row.objectName }
            concatStr = pageParams.url.match(/\/\d+/)[0]
          } else {
            if (item) {
              concatStr = '/' + item.rowParams.id
            } else {
              if (
                pageParams.url.includes('id') ||
                pageParams.url.includes('ID')
              ) {
                concatStr = '/' + row.id
              } else {
                // 根据{}进行分割。比如a/{id},则取到当前{}里面的id字符串，然后再从row[id]取对应的值
                const regex = new RegExp('{(.*?)}', 'g')
                let str = regex.exec(pageParams.url)[1]
                // 取到row里面的键值对
                concatStr = '/' + row[str]
              }
            }
          }
          this.$router.push({
            path:
              (this.$route.path.indexOf('/outer') > -1 ? '/outer' : '') +
              '/dynamic/' +
              pageParams.route +
              concatStr,
            query: params
          })
        }
      }
    },
    // 多行选中
    handleSelectionChange(val) {
      this.multipleSelection = val
      // console.log(val)
      this.$emit('handleSelectionChange', val)
    },
    // 按钮点击事件
    clickEvent(obj, row) {
      console.log(obj, 'row')
      //判断权限
      if (
        obj.type !== '4' &&
        obj.operateType != null &&
        obj.operateType !== ''
      ) {
        if (row.stateid === undefined) {
          permissionsNoState(obj.operateType, row.docId).then(response => {
            if (response !== 1) {
              this.msgError('您没有此状态下数据的【' + obj.name + '】权限！')
            } else {
              this.performActions(obj, row)
            }
          })
        } else {
          console.log('pokokoko')
          permissions(obj.operateType, row.stateid).then(response => {
            if (response !== 1) {
              this.msgError('您没有此状态下数据的【' + obj.name + '】权限！')
            } else {
              this.performActions(obj, row)
            }
          })
        }
      } else {
        this.performActions(obj, row)
      }
    },
    // 按钮点击事件执行操作
    performActions(obj, row) {
      let pageParams = JSON.parse(obj.pageParams.replace(/'/g, '"'))
      if (obj.type === '2') {
        if (obj.url) {
          let params = {}
          pageParams.url = obj.url
          params.rowParams = row
          params.pageParams = pageParams
          params.pageParams.title = obj.name
          this.$router.push({
            path: '/dynamic/' + pageParams.route + '/' + row.id,
            query: params
          })
        }
      } else {
        if (pageParams.handle == 'handleDelete') {
          this.handleDelete(obj.description, obj.url, row)
        } else if (pageParams.handle == 'handleDownload') {
          this.handleDownload(row, pageParams.type)
        } else if (pageParams.handle == 'handleConfirm') {
          this.handleConfirm(obj.url, pageParams.method, obj.description, row)
        } else if (pageParams.handle == 'handleUpdate') {
          if (pageParams.request) {
            this.handleUpdate(
              obj.url,
              pageParams.addForm,
              row.id,
              obj.description
            )
          } else {
            this.handleUpdate(obj.url, pageParams.addForm, row, obj.description)
          }
        } else if (pageParams.handle == 'handleTable') {
          this.handleTable(obj.url, pageParams, row.id, obj.description)
        } else if (pageParams.handle == 'handleNodeClick') {
          this.handleNodeClick(row.id)
        }
      }
    },
    handleNodeClick(id) {
      this.$emit('handleNodeClick', id)
    },
    /** 删除按钮操作 */
    handleDelete(title, url, row) {
      const id =
        row.name ||
        row.title ||
        row.fileName ||
        row.folderName ||
        row.userName ||
        ''
      this.$confirm(`是否确认${title} "${id}"?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(function() {
          return delData(url, row.id)
        })
        .then(() => {
          // var obj={pageNum: 1, pageSize: 10};
          this.$emit('updateList')
          this.msgSuccess('删除成功')
        })
        .catch(function() {})
    },
    handleConfirm(url, method, title, row) {
      this.$confirm(
        `确定${title}${row.name ||
          row.title ||
          row.fileName ||
          row.folderName ||
          ''}?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          baseRequest('/pms' + this.getUrl(url, row), method, {}, {}).then(
            response => {
              if (response.code == 200) {
                this.msgSuccess(response.msg)
                this.$emit('updateList')
                return true
              } else {
                this.msgError(response.msg)
                return true
              }
            }
          )
        })
        .catch(() => {
          this.msgInfo('已取消')
        })
    },
    /** 文件下载 */
    handleDownload(row, type) {
      if (type === 1) {
        if (row.path) {
          /**文件下载*/
          let xhr = new XMLHttpRequest()
          let that = this
          const downloadUrl = 'http://' + location.host + row.path
          xhr.open('GET', downloadUrl, true)
          xhr.setRequestHeader('Authorization', 'Bearer ' + getToken())
          xhr.responseType = 'blob'
          xhr.onprogress = function(event) {
            // 响应头要有Content-Length
            if (event.lengthComputable) {
              that.progress.open = true
              that.progress.percent = parseInt(
                (event.loaded / event.total) * 100
              )
            }
          }
          xhr.onload = function(oEvent) {
            var blob = new Blob([xhr.response])
            var name = row.fileName
            var url = URL.createObjectURL(blob)
            const a = document.createElement('a')
            a.setAttribute('download', name)
            a.setAttribute('href', url)
            a.click()
            that.progress.open = false
          }
          xhr.send()
          /**文件下载*/
          /**S3文件下载
          var fileUrl = row.path;
          var index = fileUrl.lastIndexOf("/");
          var bucket = fileUrl.substring(0, index);
          var downloadName = row.fileName;
          var docId = row.docId;
          getDownloadUrl(bucket, downloadName, docId).then((response) => {
            if (response.url !== "") {
              let xhr = new XMLHttpRequest();
              let that = this;
              const downloadUrl = response.url;
              xhr.open("GET", downloadUrl, true);
              xhr.setRequestHeader("Authorization", "Bearer " + getToken());
              xhr.responseType = "blob";
              xhr.onprogress = function (event) {
                // 响应头要有Content-Length
                if (event.lengthComputable) {
                  that.progress.open = true;
                  that.progress.percent = parseInt(
                    (event.loaded / event.total) * 100
                  );
                }
              };
              xhr.onload = function (oEvent) {
                var blob = new Blob([xhr.response]);
                var name = row.fileName;
                var url = URL.createObjectURL(blob);
                const a = document.createElement("a");
                a.setAttribute("download", name);
                a.setAttribute("href", url);
                a.click();
                that.progress.open = false;
              };
              xhr.send();
            } else {
              this.msgError("文件地址出错");
            }
          });
          /**S3文件下载*/
          addDownload({ docId: docId, docName: row.fileName })
        } else {
          this.msgError('文件地址出错')
        }
      } else {
        if (row.fileList.length > 1) {
          handleBatchDownload(row.fileList, row.name, row.id, this)
        } else {
          if (row.fileList[0].path) {
            /**下载*/
            let xhr = new XMLHttpRequest()
            let that = this
            const downloadUrl = 'http://' + location.host + row.fileList[0].path
            xhr.open('GET', downloadUrl, true)
            xhr.setRequestHeader('Authorization', 'Bearer ' + getToken())
            xhr.responseType = 'blob'
            xhr.onprogress = function(event) {
              // 响应头要有Content-Length
              if (event.lengthComputable) {
                that.progress.open = true
                that.progress.percent = parseInt(
                  (event.loaded / event.total) * 100
                )
              }
            }
            xhr.onload = function(oEvent) {
              var blob = new Blob([xhr.response])
              var name = row.fileList[0].fileName
              var url = URL.createObjectURL(blob)
              const a = document.createElement('a')
              a.setAttribute('download', name)
              a.setAttribute('href', url)
              a.click()
              that.progress.open = false
            }
            xhr.send()
            /**下载*/
            /**舜宇S3下载
            var fileUrl = row.fileList[0].path;
            var index = fileUrl.lastIndexOf("/");
            var bucket = fileUrl.substring(0, index);
            var downloadName = row.fileList[0].fileName;
            var docId = row.id;
            getDownloadUrl(bucket, downloadName, docId).then((response) => {
              if (response.url !== "") {
                let xhr = new XMLHttpRequest();
                let that = this;
                const downloadUrl = "http://" + location.host + response.url;
                xhr.open("GET", downloadUrl, true);
                xhr.setRequestHeader("Authorization", "Bearer " + getToken());
                xhr.responseType = "blob";
                xhr.onprogress = function (event) {
                  // 响应头要有Content-Length
                  if (event.lengthComputable) {
                    that.progress.open = true;
                    that.progress.percent = parseInt(
                      (event.loaded / event.total) * 100
                    );
                  }
                };
                xhr.onload = function (oEvent) {
                  var blob = new Blob([xhr.response]);
                  var name = row.fileList[0].fileName;
                  var url = URL.createObjectURL(blob);
                  const a = document.createElement("a");
                  a.setAttribute("download", name);
                  a.setAttribute("href", url);
                  a.click();
                  that.progress.open = false;
                };
                xhr.send();
              } else {
                this.msgError("文件地址出错");
              }
            });
            /**舜宇S3下载*/
          } else {
            this.msgError('文件地址出错')
          }
        }
        addDownload({ docId: row.id, docName: row.name })
      }
    },
    handleUpdate(url, str, row, title) {
      let info = { url, str, id: row, title }
      this.$emit('editChanged', info)
    },
    handleTable(url, str, id, title) {
      let info = { url, str, id: id, title }
      this.$emit('openTable', info)
    },
    handleChange(val) {
      this.parent.submitData[val.id] = { ids: val.id, userIds: val.userId }
    },
    //preview预览
    preview(previewUrl, stateId, docId, fileId) {
      this.previewActions(previewUrl)
      // if (stateId === undefined) {
      //   permissionsNoState("views", docId).then((response) => {
      //     if (response !== 1) {
      //       this.msgError("您没有此状态下数据的【预览】权限！");
      //     } else {
      //       this.previewActions(previewUrl);
      //       if (docId && fileId) {
      //         previewRecord(docId, fileId);
      //       }
      //     }
      //   });
      // } else {
      //   permissions("views", stateId).then((response) => {
      //     if (response !== 1) {
      //       this.msgError("您没有此状态下数据的【预览】权限！");
      //     } else {
      //       this.previewActions(previewUrl);
      //       if (docId && fileId) {
      //         previewRecord(docId, fileId);
      //       }
      //     }
      //   });
      // }
    },
    // 下拉操作统一回调
    handleCommand(e) {
      this.clickEvent(e.btn, e.row)
    },
    previewActions(previewUrl) {
      if (previewUrl == null || previewUrl === '') {
        this.msgError('预览预览地址错误！')
      }
      var close = false
      const Loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      setTimeout(() => {
        if (!close) {
          Loading.close()
          this.msgError('预览加载超时,请稍后重试或联系管理员。')
        }
      }, 10000)
      const screenWidth = parseInt(0.5 * document.body.clientWidth) // 预览窗口宽度
      const screenHeight = parseInt(0.6 * document.documentElement.clientHeight) // 预览窗口高度
      var strLength = previewUrl.length
      var str = previewUrl.slice(previewUrl.indexOf('.') + 1, strLength)

      /** 35 预览
      //let previewParam = {};
      var url = previewParameter.preview_path_zs;
      //水印
      var watermark = this.$store.state.user.name;

      let xhr = new XMLHttpRequest();
      xhr.open("POST", url, true); //建立间接，要求异步响应
      xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); //设置为表单方式提交
      xhr.onreadystatechange =  ()=>{
        //绑定响应状态事件监听函数
        if (xhr.readyState == 4) {
          //监听readyState状态
          if (xhr.status == 200 || xhr.status == 0) {
            //监听HTTP状态码
            Loading.close();
            close = true
            var rdata = JSON.parse(xhr.responseText);
            if (rdata.success) {
              window.open(
                rdata.viewurl,
                createUniqueString(),
                `height=${screenHeight},
                            width=${screenWidth},
                            top=${0.4 * screenHeight},
                            left=${0.5 * screenWidth}`
              );
            }else{
              this.msgError(rdata.msg);
            }
          }
        }
      };
      let data = Base64.encode(previewUrl);
      xhr.send("file=" + encodeURIComponent(data)+"&watermark="+watermark+"&cache=false"); //发送请求
      /** 35 预览*/

      /** 120 预览*/
      let strArray = ['img', 'png', 'html']
      var url = ''
      if (previewUrl.indexOf('http://') < 0) {
        url = this.settings.fileUrl + previewUrl
      } else {
        url = previewUrl
      }
      //console.log(url);
      if (strArray.indexOf(str) > -1) {
        Loading.close()
        close = true
        if (0) url = 'http://localhost:81' + previewUrl
        window.open(
          url,
          createUniqueString(),
          `height=${screenHeight},
                    width=${screenWidth},
                    top=${0.4 * screenHeight},
                    left=${0.5 * screenWidth}`
        )
      } else {
        Loading.close()
        close = true
        window.open(
          this.settings.previewUrl +
            '/onlinePreview?url=' +
            encodeURIComponent(Base64.encode(url)),
          createUniqueString(),
          `height=${screenHeight},
                    width=${screenWidth},
                    top=${0.4 * screenHeight},
                    left=${0.5 * screenWidth}`
        )
      }
      /** 120 预览*/
    },
    checkboxInit(row) {
      return !this.uncheck.includes(row.id)
    },
    // 表格自适应更新方法
    tableresize() {
      if (this.$refs.mutipleTable) {
        let newDiff =
          this.diff + (this.$route.path.indexOf('outer') > -1 ? 50 : 0)
        // let el = this.$refs.mutipleTable.$el
        if (this.scroll == 'false') {
          this.maxHeight =
            this.app.screenHeight - newDiff > 200
              ? this.app.screenHeight - newDiff
              : 200
        } else if (this.scroll == 'fix') {
          this.maxHeight = 200
        } else {
          this.maxHeight =
            this.$parent.$el.offsetHeight - newDiff > 200
              ? this.$parent.$el.offsetHeight - newDiff
              : 200
        }
        // if (
        //   this.scroll ||
        //   this.$refs.mutipleTable.$refs.bodyWrapper.scrollHeight >
        //     this.maxHeight
        // )
        //   this.maxHeight =
        //     this.$parent.$el.offsetHeight - this.diff > 100
        //       ? this.$parent.$el.offsetHeight - this.diff
        //       : 100;
        // this.$refs.mutipleTable.children[2].scrollTo(0,0)
        this.$refs.mutipleTable.$refs.bodyWrapper.scrollTo(0, 0)
      }
      this.widthUpdate(this.columns)
    },
    // 表格宽度自适应计算
    widthUpdate(val) {
      if (val && this.$parent.$el) {
        var parentWidth = this.$parent.$el.offsetWidth
        var sum = 0
        for (let column of val) {
          if (column.width) {
            if (column.show) sum += Number(column.width)
          } else {
            sum = 0
            break
          }
        }
        if (this.options.mutiSelect) parentWidth -= 48
        if (
          this.operates.list.filter(
            _x => _x.status === '1' && _x.location === '1'
          ).length > 0
        ) {
          parentWidth -= 150
        }
        if (sum && sum < parentWidth) {
          this.hasResize = true
          for (let column of val) {
            column.showWidth = (column.width / sum) * parentWidth
          }
        } else {
          this.hasResize = false
        }
      }
    },
    // 图片预览
    imgPreview(url) {
      const newwin = window.open(
        '/imgPreview',
        createUniqueString(),
        `height=${
          0.5 * this.app.screenHeight > 600 ? 0.5 * this.app.screenHeight : 600
        },
                                    width=${
                                      0.5 * this.app.screenWidth > 960
                                        ? 0.5 * this.app.screenWidth
                                        : 960
                                    },
                                    top=${0.2 * this.app.screenHeight},
                                    left=${0.2 * this.app.screenWidth}`
      )
      newwin.imgs = url
    },
    handleAddLine() {
      this.list.push({})
    },
    // 表格底部合计方法
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        const values = data.map(item =>
          item[column.property]
            ? Number(this.dataFormat(column.property, item[column.property]))
            : 0
        )
        if (values.every(value => !isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return (prev * 100 + curr * 100) / 100
            } else {
              return prev
            }
          }, 0)
        } else {
          sums[index] = ''
        }
      })
      return sums
    },
    // 文件上传成功回调
    handleFileSuccess(response, file, fileList, row, btn) {
      console.log(fileList)
      if (fileList.every(file => file.response != undefined)) {
        // 更新
        if (btn.operateType.indexOf('Update') > -1) {
          row.fileList = fileList.map(item => {
            return {
              fileName: item.name,
              path: item.response ? item.response.fileName : '',
              fileSize: item.size
            }
          })
        } else {
          // 叠加上传
          if (row.fileList == undefined) {
            row.fileList = []
          }
          row.fileList = row.fileList.concat(
            fileList.map(item => {
              return {
                fileName: item.name,
                path: item.response ? item.response.fileName : '',
                fileSize: item.size
              }
            })
          )
        }
        updateData(this.getUrl(btn.url), row)
          .then(() => {
            this.msgSuccess('更新成功')
            this.refreshCurrent()
          })
          .catch(err => {
            this.msgError('更新失败')
            console.log(err)
          })
      }
    },
    handleFileError() {
      this.msgInfo('文件上传失败')
    },
    handleStatusChange(row, item) {
      let obj = {}
      obj[item.prop] = row[item.prop]
      obj.id = row.id
      let text = row[item.prop] == '0' ? '启用' : '停用'
      this.$confirm('确认要' + text + '吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(function() {
          if (!item.url) return this.msgSuccess('缺少URL地址参数')
          return changeStatus('/pms/' + item.url, obj)
        })
        .then(() => {
          this.msgSuccess(text + '成功')
        })
        .catch(function() {
          row[item.prop] = row[item.prop] === '0' ? '1' : '0'
        })
      // console.log(row)
      // console.log(item)
    }
  }
}
</script>

<style lang="scss">
.operate-group {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
}
.el-table th.is-leaf,
.el-table td {
  border-bottom: 0;
}
.link-type {
  text-decoration: underline;
  cursor: pointer;
}
.item {
  padding: 0 3px;
}
.el-table .el-table__expand-icon .el-icon-arrow-right:before {
  content: '';
  background: url('../../assets/image/add.png');
  width: 14px;
  height: 14px;
  display: inline-block;
  background-size: cover;
}
.el-table .el-table__expand-icon--expanded {
  transform: rotate(0);
}
.el-table .el-table__expand-icon--expanded .el-icon-arrow-right:before,
.el-table .el-table__placeholder:before {
  content: '';
  background: url('../../assets/image/minus.png');
  width: 14px;
  height: 14px;
  display: inline-block;
  background-size: cover;
}
.el-table .el-table__expand-icon {
  line-height: 30px !important;
  margin-right: 5px !important;
}
.el-table .el-table__placeholder {
  height: 12px;
  width: 12px;
  margin-right: 10px;
}
.el-table--enable-row-hover .el-table__body tr:hover > td {
  background-color: #d2defc !important;
}
.el-table__row--striped td {
  background-color: #fafafa !important;
}
.el-progress-bar__innerText {
  line-height: 26px;
}
.el-rate {
  height: auto;
  line-height: 1;
}
.cell {
  width: 100% !important;
}
.el-image__error {
  display: none;
}
.el-image-viewer__close {
  top: 60px;
  right: 15%;
}
.el-progress-bar__innerText {
  color: #333;
}
</style>
